import Vue from 'vue'
import VueRouter from 'vue-router'
import { getUserByTokenApi } from '../request/httpaip'
import store from '../store'
import { sepet } from '../store/mutations'

const originalReplace = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalReplace.call(this, location).catch(err => err)
}
// 路由守卫重复进入两次，报错（虽然页面还可以运行)网上解决代码

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '../views/Login/Login.vue')
  },
  // {
  //   path: '/home',
  //   name: 'Home',
  //   component: () => import(/* webpackChunkName: "Home" */ '../views/Home.vue'),
  //   children:[
  //       {
  //         path: '/good',
  //         name: 'Good',
  //         component: () => import(/* webpackChunkName: "good" */ '../views/Good.vue')
  //       },
  //       {
  //         path: '/category',
  //         name: 'Category',
  //         component: () => import(/* webpackChunkName: "category" */ '../views/Category.vue')
  //       },
  //       {
  //         path: '/brand',
  //         name: 'Brand',        
  //         component: () => import(/* webpackChunkName: "brand" */ '../views/Brand.vue')
  //       },
  //       {
  //         path: '/attribute',
  //         name: 'Attribute',
  //         component: () => import(/* webpackChunkName: "attribute" */ '../views/Attribute.vue')
  //       },
  //       {
  //         path: '/order',
  //         name: 'Order',
  //         component: () => import(/* webpackChunkName: "order" */ '../views/Order.vue')
  //       },
  //       {
  //         path: '/topic',
  //         name: 'Topic',
  //         component: () => import(/* webpackChunkName: "topic" */ '../views/Topic.vue')
  //       },
  //       {
  //         path: '/statdata',
  //         name: 'Statdata',
  //         component: () => import(/* webpackChunkName: "statdata" */ '../views/Statdata.vue')
  //       },
  //       {
  //         path: '/user',
  //         name: 'User',
  //         component: () => import(/* webpackChunkName: "user" */ '../views/User.vue')
  //       },  
  //   ]
  // }

  // {
  //   path: '/',
  //   name: 'Home',
  //   component: Home
  // },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]
// 抽取全路由表
let routerArr = [
  {
    path: '/good',
    name: 'Good',
    component: () => import(/* webpackChunkName: "good" */ '../views/Good/Good.vue')
  },
  {
    path: '/addgood',
    name: 'AddGood',
    component: () => import(/* webpackChunkName: "addgood" */ '../views/Good/AddGood.vue')
  },
  {
    path: '/editgood',
    name: 'EditGood',
    component: () => import(/* webpackChunkName: "editgood" */ '../views/Good/EditGood.vue')
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import(/* webpackChunkName: "category" */ '../views/Category/Category.vue')
  },
  {
    path: '/addcategory',
    name: 'AddCategory',
    component: () => import(/* webpackChunkName: "addcategory" */ '../views/Category/AddCategory.vue')
  },
  {
    path: '/editcategory',
    name: 'EditCategory',
    component: () => import(/* webpackChunkName: "editcategory" */ '../views/Category/EditCategory.vue')
  },
  {
    path: '/brand',
    name: 'Brand',
    component: () => import(/* webpackChunkName: "brand" */ '../views/Brand/Brand.vue')
  },
  {
    path: '/addbrand',
    name: 'Addbrand',
    component: () => import(/* webpackChunkName: "addbrand" */ '../views/Brand/Addbrand.vue')
  },
  {
    path: '/editbrand',
    name: 'Editbrand',
    component: () => import(/* webpackChunkName: "editbrand" */ '../views/Brand/Editbrand.vue')
  },
  {
    path: '/attribute',
    name: 'Attribute',
    component: () => import(/* webpackChunkName: "attribute" */ '../views/Attribute/Attribute.vue')
  },
  {
    path: '/addattribute',
    name: 'AddAttribute',
    component: () => import(/* webpackChunkName: "addattribute" */ '../views/Attribute/AddAttribute.vue')
  },
  {
    path: '/editattribute',
    name: 'EditAttribute',
    component: () => import(/* webpackChunkName: "editattribute" */ '../views/Attribute/EditAttribute.vue')
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import(/* webpackChunkName: "order" */ '../views/Order/Order.vue')
  },
  {
    path: '/topic',
    name: 'Topic',
    component: () => import(/* webpackChunkName: "topic" */ '../views/Topic/Topic.vue')
  },
  {
    path: '/addtopic',
    name: 'AddTopic',
    component: () => import(/* webpackChunkName: "addtopic" */ '../views/Topic/AddTopic.vue')
  },
  {
    path: '/edittopic',
    name: 'EditTopic',
    component: () => import(/* webpackChunkName: "edittopic" */ '../views/Topic/EditTopic.vue')
  },
  {
    path: '/statdata',
    name: 'Statdata',
    component: () => import(/* webpackChunkName: "statdata" */ '../views/Statdata/Statdata.vue')
  },
  {
    path: '/user',
    name: 'User',
    component: () => import(/* webpackChunkName: "user" */ '../views/User/User.vue')
  },
 

]
// 设置全路由表(设置为键值对进行对比减少循环)
let goodrouterArr = routerArr.reduce((prev, current) => {
  let key = current.path;// 可访问路径
  let val = current; //数据本身
  prev[key] = val
  //先在把path提取 以键值对的对象存起 简化判断
  return prev
}, {})


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//封装生成路由表
const newRouterRender = () => {
  let newRouterArr = [];
  let per = store.state.por
  // per --用户信息生成路由表
  for (var n = 0; n < per.length; n++) {
    if (goodrouterArr[per[n].path]) {//判断是否有这个路由路径有生成,没有排除
      newRouterArr.push(goodrouterArr[per[n].path])// 添加到新数组(生成权限路由)
    }
  }
  // 按照路由规定把获取到路由权限添加到真正的路由表中
  router.addRoutes([
    {
      path: '/home',
      name: 'Home',
      component: () => import(/* webpackChunkName: "Home" */ '../views/Home/Home.vue'),
      children: newRouterArr,
      //把获取到的权限路由newRouter添加到children中,真正生成前端路由权限(用户路由表).
    },
  ])
}




// 设置路由守卫
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  //在路由中获取token,---用于判断用户是否登录
  console.log(to, from);
  console.log(store.state);
  if (token && store.state.por.length === 0) {
    //需要重新获取登录用户信息的条件 1 token存在(有token), 2vuex中里面权限列表没有数据时
    getUserByTokenApi().then(res => {
      //调用接口👆发送网路请求重新获取用户信息(权限列表)
      if (res.errno === 0) {
        store.commit(sepet, res.data.menu)
        //把获取到用户信息储存到vuex里面

        newRouterRender() //调用封装生成路由表

      }
      next(to)//next(to)路由再转入路由循环一次,使其把权限存到vuex之后再跳转页面(以免没有获取权限就直接跳转了)
    })
  } else if (!token && to.path !== "/login") {
    //设置退出时没有token转回登录页👆,和跳转时所在页不是登录页--不然就是死循环
    next('/login')//跳转登录页
  } else if (token && store.state.por.length > 0 && to.path == "/home" && from.path == '/login') {
    // 判断1有token(已登录) 2vuex中有路由权限 3跳转到home页面 4来自登录页login

    newRouterRender() //调用封装生成路由表
    
    next(store.state.por[0].path)
  } else if (token && to.path == "/login") {
    // 判断有token(已登录) 且想跳转登录页login---业务流程登录后不可跳转
    next('/home')
  }
  else {
    next() //没有token就直接跳转即可
  }

})
export default router
